odoo.define('er.timeline', function (require) {
"use strict";

    var core = require('web.core');
    var form_common = require('web.form_common');
    var formats = require('web.formats');
    var Model = require('web.Model');
    var Widget = require('web.Widget');
    var FormView = require('web.FormView');
    var ListView = require("web.ListView");

    var Comment = new Model('tyibs.er.work.order.comment');
    var QWeb = core.qweb;

    var TimeLineItemWidget = Widget.extend({
        template:"TimeLineItemWidget",

        init:function(parent, record, item_direction){
            this._super(parent);
            this.record = record;
            this.set_do_time();
            this.item_direction = item_direction;
            this.stage_icon = "";
            this.stage_icon_color = "";
            this.format_data();
        },
        set_do_time: function () {
            var self = this;
            self.do_time = new Date(self.record.do_time);
            self.do_time.setHours(self.do_time.getHours() + 8);
            self.do_time = self.do_time.getFullYear().toString()
                + "-" + self.format_do_time(self.do_time.getMonth() + 1)
                + "-" + self.format_do_time(self.do_time.getDate())
                + " " + self.format_do_time(self.do_time.getHours())
                + ":" + self.format_do_time(self.do_time.getMinutes())
                + ":" + self.format_do_time(self.do_time.getSeconds())
        },
        format_do_time: function (i) {
            return i > 9 ? i.toString() : '0' + i.toString();
        },
        format_data:function(){
            var self = this;
            var work_order_sate = {
                    'unknown': {'name':'未知阶段','icon':'fa fa-question','icon_color':'primary'},
                    'draft': {'name':'尚未接警','icon':'fa fa-phone','icon_color':'danger'},
                    'center_received':{'name':'中心接警','icon':'fa-user','icon_color':'warning'},
                    "command_and_dispatch":{'name':"指挥调度",'icon':'fa fa-car','icon_color':'info'},
                    "keep_track_rescure":{'name':"救援跟踪",'icon':'fa fa-headphones','icon_color':'success'},
                    "archive":{'name':"完成归档",'icon':'fa fa-archive','icon_color':'active'}
            };
            var state = self.record['stage'] ? self.record['stage'] : "unknown";

            self.record['stage'] = work_order_sate[state]['name'];
            self.stage_icon = work_order_sate[state]['icon'];
            self.stage_icon_color = work_order_sate[state]['icon_color'];
            self.record['content'] = self.split_content(self.record['content']);
        },
        split_content:function(content){
            if(content==null || content==undefined || content==""){
                return "";
            }else{
                return content.split("\n").map(function (line) {
                    return  line;
                }).join("<br/>");
            }
        }
    });

    var TimeLineWidget = form_common.AbstractField.extend({
        template:"TimeLineWidget",
        events:{
            'click button.btn_add_timeline':function(){
				//获取当前表单及Id值
				var id_index = this.field_manager.ViewManager.dataset.index;
				console.log(this.field_manager.ViewManager.dataset.ids[id_index]);
				console.log(this.field_manager.ViewManager.dataset.model);
                this.do_action({
                    type: 'ir.actions.act_window',
                    res_model: "tyibs.er.work.order.comment.wizard",
                    view_type:"form",
                    view_mode:"form",
                    views: [[false, 'form']],
                    target: 'new',
                    context:{
                        'default_res_model':this.field_manager.ViewManager.dataset.model,
                        'default_res_id':this.field_manager.ViewManager.dataset.ids[id_index],
                    }
                });
            }
        },
        render_value: function() {
           var self = this;
           var comment_ids = self.get("value");
           // 必须做一次清空，否则新建对象或打开其他对象时不会自动更新
           self.$("ul.timeline").empty();
           if(comment_ids.length<1){
               return;
           }
           Comment.query(['contact','phone','stage','do_time','content','has_record'])
               .filter([['id','in',comment_ids]])
               .order_by("do_time")
               .all()
               .then(function(records){
                   records.forEach(function(record,index){
                      var item_direction = (index+1)%2==0?"timeline-inverted":"";
                      var stage_icon = "fa-user";
                      var item = new TimeLineItemWidget(self,record, item_direction,stage_icon); 
                      item.appendTo(self.$("ul.timeline"));
                   });
               });
        }
    });

    /*
    var load_baidu_map_script = function(){
        console.log("load_baidu_map_script start");
        var script = document.createElement("script");
        script.src = "http://api.map.baidu.com/api?v=2.0&ak=RtDOZPq5ifnbLaKWGOYnLL6wNZdPE9ZA";
        document.body.appendChild(script);
        console.log("load_baidu_map_script end");
    };

    window.onload = load_baidu_map_script;
    */
    /*
    var MyWidget = form_common.FormWidget.extend({
        init: function(field_manager, node) {
            this._super(field_manager, node);
            console.log("init called", node);
        },
        start: function () {
            this._super();
            this.field_manager.on("field_changed:comment_ids",this,this.show_time_line);
            console.log("Hello MyWidget");

        },
        show_time_line:function(){
            console.log("show_time_line called");
            console.log(this.field_manager.get_field_value('comment_ids'));
            console.log(this.session.active_id);
        }
    });
    core.form_tag_registry.add('my_widget', MyWidget);
    */

    core.form_widget_registry.add('timeline', TimeLineWidget);

    return {
        TimeLineWidget: TimeLineWidget,
        //MyWidget: MyWidget
    };
});
